//
//  registerViewController.m
//  ioschishan
//
//  Created by 千翼网络科技 on 2017/7/12.
//  Copyright © 2017年 qianyi. All rights reserved.
//

#import "registerViewController.h"
#import "FS_MyChangrSexViewController.h"
#import "setPhoneViewController.h"
#import "registerAgreementViewController.h"

#import "STPhotoKitController.h"
#import "UIImagePickerController+ST.h"
#import "UIButton+AddAction.h"
#import "ICN_HeadImageSelView.h"

@interface registerViewController ()<UINavigationControllerDelegate,UIImagePickerControllerDelegate,numDelegate,STPhotoKitDelegate>{

    UIView *grayView;
    
}

@property(nonatomic,strong) UIView *shadowView;
@property(nonatomic,strong) UIView *dateBgView;
@property(nonatomic,strong) UIDatePicker *myDatePicker;

@property (nonatomic,strong) UIButton *headImgBtn;
@property (nonatomic,strong) UITextField *nameTextField;
@property (nonatomic,strong) UILabel *birthdayLabel;
@property (nonatomic,strong) UILabel *sexLabel;
@property (nonatomic,strong) UITextField *pwdTextField;

@property (nonatomic, strong) ICN_HeadImageSelView *changeHeadImageView;
@property (nonatomic, strong) UIImage *image;

@end

@implementation registerViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self initView];
    [self datePicker];
}

#pragma mark ----------------------- init ---------------------

- (void)datePicker{
    
    _dateBgView = [[UIView alloc]initWithFrame:CGRectMake(0, scrHeight(), scrWidth(), scrHeight() - screenScale(200) - screenScale(44 * 5))];
    _dateBgView.backgroundColor = getColor(@"ffffff");
    [[[UIApplication sharedApplication]keyWindow] addSubview:_dateBgView];
    
    UIButton *cancelBtn = [ConfigXp buttonWithFrame:CGRectMake(0, 0, screenScale(100), screenScale(44))
                                              title:@"取消"
                                         titleColor:getColor(@"222222")
                                               font:get4sFont(15)
                                    backgroundColor:[UIColor clearColor]
                                              image:nil];
    [cancelBtn addTarget:self action:@selector(dateCancelBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [_dateBgView addSubview:cancelBtn];
    
    UIButton *finishBtn = [ConfigXp buttonWithFrame:CGRectMake(scrWidth() - screenScale(100), 0, screenScale(100), screenScale(44))
                                              title:@"完成"
                                         titleColor:getColor(@"222222")
                                               font:get4sFont(15)
                                    backgroundColor:[UIColor clearColor]
                                              image:nil];
    [finishBtn addTarget:self action:@selector(dateFinishBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [_dateBgView addSubview:finishBtn];
    
    ///
    
    self.myDatePicker = [[UIDatePicker alloc] initWithFrame:CGRectMake(0, scrHeight(), scrWidth(), scrHeight() - screenScale(200) - screenScale(44 * 6))];
    self.myDatePicker.datePickerMode = UIDatePickerModeDate;
    self.myDatePicker.backgroundColor = [UIColor colorWithRed:239/255.f
                                                        green:239/255.f
                                                         blue:244.0/255.f
                                                        alpha:1.0];
    self.myDatePicker.hidden = YES;
    [[[UIApplication sharedApplication]keyWindow] addSubview:self.myDatePicker];
}

- (void)initView{

    self.title = @"个人资料";
    
    _shadowView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, scrWidth(), scrHeight())];
    _shadowView.backgroundColor = [UIColor blackColor];
    _shadowView.alpha = 0.1;
    _shadowView.hidden = YES;
    [[[UIApplication sharedApplication]keyWindow] addSubview:_shadowView];
    
    /// 头像
    
    _headImgBtn = [ConfigXp buttonWithFrame:CGRectMake(screenScale(148), screenScale(30), screenScale(80), screenScale(80))
                                      title:nil
                                 titleColor:nil
                                       font:nil
                            backgroundColor:nil
                                      image:[UIImage imageNamed:@"add_image_icon"]];
    [_headImgBtn addTarget:self action:@selector(headImgBtnClick) forControlEvents:UIControlEventTouchUpInside];
    _headImgBtn.layer.cornerRadius = screenScale(40);
    [self.view addSubview:_headImgBtn];
    
    _nameTextField = [[UITextField alloc]init];
    _nameTextField.placeholder = @"填写昵称";
    _nameTextField.textColor = getColor(@"9b9b9b");
    _nameTextField.font = get4sFont(12);
    _nameTextField.clearButtonMode = UITextFieldViewModeWhileEditing;
    [_nameTextField setValue:getColor(@"9b9b9b") forKeyPath:@"_placeholderLabel.textColor"];
    [self.view addSubview:_nameTextField];
    [_nameTextField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.view).with.offset(screenScale(141));
        make.left.mas_equalTo(self.view).with.offset(screenScale(25));
        make.right.mas_equalTo(self.view).with.offset(screenScale(-25));
        make.height.mas_equalTo(screenScale(14));
    }];
    
    UIView *nameThread = [[UIView alloc]initWithFrame:CGRectMake(screenScale(20), screenScale(172), scrWidth() - screenScale(40), screenScale(0.5))];
    nameThread.backgroundColor = getThreadColor();
    [self.view addSubview:nameThread];
    
    /// 生日
    
    _birthdayLabel = [ConfigXp labelWithFrame:CGRectZero
                                         text:@"选择生日"
                                    textColor:getColor(@"9b9b9b")
                                         font:get4sFont(12)
                                textAlignment:NSTextAlignmentLeft
                              backgroundColor:[UIColor clearColor]];
    [self.view addSubview:_birthdayLabel];
    [_birthdayLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.view).with.offset(screenScale(190));
        make.left.mas_equalTo(self.view).with.offset(screenScale(25));
        
        
    }];
    
    UIImageView *rightImg = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"arrow_icon"]];
    [self.view addSubview:rightImg];
    [rightImg mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.view).with.offset(screenScale(191));
        make.right.mas_equalTo(self.view).with.offset(screenScale(-30));
        make.width.mas_equalTo(screenScale(12));
        make.height.mas_equalTo(screenScale(12));
    }];
    
    UIButton *birthdayBtn = [ConfigXp buttonWithFrame:CGRectZero
                                                title:nil
                                           titleColor:nil
                                                 font:nil
                                      backgroundColor:nil
                                                image:nil];
    [birthdayBtn addTarget:self action:@selector(birthdayBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:birthdayBtn];
    [birthdayBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.view).with.offset(screenScale(173));
        make.left.mas_equalTo(self.view).with.offset(0);
        make.width.mas_equalTo(scrWidth());
        make.height.mas_equalTo(screenScale(48));
    }];
    
    UIView *birthdayThread = [[UIView alloc]initWithFrame:CGRectMake(screenScale(20), screenScale(222), scrWidth() - screenScale(40), screenScale(0.5))];
    birthdayThread.backgroundColor = getThreadColor();
    [self.view addSubview:birthdayThread];
    
    /// 性别
    
    _sexLabel = [ConfigXp labelWithFrame:CGRectZero
                                         text:@"选择性别"
                                    textColor:getColor(@"9b9b9b")
                                         font:get4sFont(12)
                                textAlignment:NSTextAlignmentLeft
                              backgroundColor:[UIColor clearColor]];
    [self.view addSubview:_sexLabel];
    [_sexLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.view).with.offset(screenScale(240));
        make.left.mas_equalTo(self.view).with.offset(screenScale(25));
        
        
    }];
    
    UIImageView *sexImg = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"arrow_icon"]];
    [self.view addSubview:sexImg];
    [sexImg mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.view).with.offset(screenScale(241));
        make.right.mas_equalTo(self.view).with.offset(screenScale(-30));
        make.width.mas_equalTo(screenScale(12));
        make.height.mas_equalTo(screenScale(12));
    }];
    
    UIButton *sexBtn = [ConfigXp buttonWithFrame:CGRectZero
                                                title:nil
                                           titleColor:nil
                                                 font:nil
                                      backgroundColor:nil
                                                image:nil];
    [sexBtn addTarget:self action:@selector(sexBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:sexBtn];
    [sexBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.view).with.offset(screenScale(221));
        make.left.mas_equalTo(self.view).with.offset(0);
        make.width.mas_equalTo(scrWidth());
        make.height.mas_equalTo(screenScale(48));
    }];
    
    UIView *sexThread = [[UIView alloc]initWithFrame:CGRectMake(screenScale(20), screenScale(272), scrWidth() - screenScale(40), screenScale(0.5))];
    sexThread.backgroundColor = getThreadColor();
    [self.view addSubview:sexThread];
    
    /// 密码
    
    _pwdTextField = [[UITextField alloc]init];
    _pwdTextField.placeholder = @"请输入6-16位密码";
    _pwdTextField.textColor = getColor(@"9b9b9b");
    _pwdTextField.font = get4sFont(12);
    _pwdTextField.secureTextEntry = YES;
    _pwdTextField.keyboardType = UIKeyboardTypeNumbersAndPunctuation;
    _pwdTextField.clearButtonMode = UITextFieldViewModeWhileEditing;
    [_pwdTextField setValue:getColor(@"9b9b9b") forKeyPath:@"_placeholderLabel.textColor"];
    [self.view addSubview:_pwdTextField];
    [_pwdTextField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.view).with.offset(screenScale(290));
        make.left.mas_equalTo(self.view).with.offset(screenScale(25));
        make.right.mas_equalTo(self.view).with.offset(screenScale(-60));
        make.height.mas_equalTo(screenScale(14));
    }];
    
    UIButton *secureTextEntryBtn = [ConfigXp buttonWithFrame:CGRectZero
                                           title:nil
                                      titleColor:nil
                                            font:nil
                                 backgroundColor:nil
                                           image:[UIImage imageNamed:@"display_icon"]];
    secureTextEntryBtn.selected = YES;
    [secureTextEntryBtn setImage:[UIImage imageNamed:@"hide_icon"] forState:UIControlStateSelected];
    [secureTextEntryBtn addTarget:self action:@selector(secureTextEntryBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:secureTextEntryBtn];
    [secureTextEntryBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.view).with.offset(screenScale(288));
        make.right.mas_equalTo(self.view).with.offset(screenScale(-27));
        make.width.mas_equalTo(screenScale(20));
        make.height.mas_equalTo(screenScale(20));
    }];
    
    UIView *pwdThread = [[UIView alloc]initWithFrame:CGRectMake(screenScale(20), screenScale(322), scrWidth() - screenScale(40), screenScale(0.5))];
    pwdThread.backgroundColor = getThreadColor();
    [self.view addSubview:pwdThread];
    
    /// btn
    
    UIButton *nextBtn = [ConfigXp buttonWithFrame:CGRectMake(screenScale(20), screenScale(348), scrWidth() - screenScale(40), screenScale(44))
                                            title:@"继续"
                                       titleColor:getColor(@"ffffff")
                                             font:get4sFont(14)
                                  backgroundColor:getColor(@"3a95ff")
                                            image:nil];
    nextBtn.layer.cornerRadius = screenScale(3);
    [nextBtn addTarget:self action:@selector(nextBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:nextBtn];
    
    UILabel *messageLabel = [ConfigXp labelWithFrame:CGRectZero
                                                text:@"注册即表示同意"
                                           textColor:getColor(@"9b9b9b")
                                                font:get4sFont(10)
                                       textAlignment:NSTextAlignmentLeft
                                     backgroundColor:[UIColor clearColor]];
    [self.view addSubview:messageLabel];
    [messageLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.view).with.offset(screenScale(407));
        make.left.mas_equalTo(self.view).with.offset(screenScale(86));
        
        make.height.mas_equalTo(screenScale(12));
    }];
    
    UIButton *messageBtn = [ConfigXp buttonWithFrame:CGRectZero
                                               title:@"《天边彩虹用户协议》"
                                          titleColor:getColor(@"3a95ff")
                                                font:get4sFont(10)
                                     backgroundColor:[UIColor clearColor]
                                               image:nil];
    [messageBtn addTarget:self action:@selector(messageBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:messageBtn];
    [messageBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.view).with.offset(screenScale(407));
        make.left.mas_equalTo(self.view).with.offset(screenScale(170));
        
        make.height.mas_equalTo(screenScale(12));
    }];
    
}

#pragma mark ----------------------- click ---------------------

- (void)dateCancelBtnClick{
    
    [UIView animateWithDuration:0.5 animations:^{
        
        [UIView beginAnimations:@"move" context:nil];
        [UIView setAnimationDuration:0.75];
        [UIView setAnimationDelegate:self];
        
        _shadowView.alpha = 0.1;
        self.myDatePicker.frame = CGRectMake(0, scrHeight(), scrWidth(), scrHeight() - screenScale(200) - screenScale(44 * 6));
        _dateBgView.frame = CGRectMake(0, scrHeight(), scrWidth(), scrHeight() - screenScale(200) - screenScale(44 * 5));
        
        _shadowView.hidden = YES;
        
        [UIView commitAnimations];
    }];
}

- (void)dateFinishBtnClick{
    
    //获取挑选的日期
    NSDate *date =_myDatePicker.date;
    NSDateFormatter *dateForm = [[NSDateFormatter alloc]init];
    //设定转换格式
    dateForm.dateFormat =@"yyyy-MM-dd";
    //由当前获取的NSDate数据，转换为日期字符串，显示在私有成员变量_textField上
    //    _textField.text = [dateForm stringFromDate:date];
    
    _birthdayLabel.text = [dateForm stringFromDate:date];
    
    [UIView animateWithDuration:0.5 animations:^{
        
        [UIView beginAnimations:@"move" context:nil];
        [UIView setAnimationDuration:0.75];
        [UIView setAnimationDelegate:self];
        
        _shadowView.alpha = 0.1;
        self.myDatePicker.frame = CGRectMake(0, scrHeight(), scrWidth(), scrHeight() - screenScale(200) - screenScale(44 * 6));
        _dateBgView.frame = CGRectMake(0, scrHeight(), scrWidth(), scrHeight() - screenScale(200) - screenScale(44 * 5));
        
        _shadowView.hidden = YES;
        
        [UIView commitAnimations];
    }];
    
}

- (void)headImgBtnClick{

    NSLog(@"上传头像");
    [self editImageSelected];
    
}

- (void)birthdayBtnClick{

    NSLog(@"生日");
    
    [self.view endEditing:YES];
    
    [UIView animateWithDuration:0.5 animations:^{
        
        [UIView beginAnimations:@"move" context:nil];
        [UIView setAnimationDuration:0.75];
        [UIView setAnimationDelegate:self];
        
        _shadowView.alpha = 0.6;
        
        self.myDatePicker.frame = CGRectMake(0, screenScale(200) + screenScale(44 * 6), scrWidth(), scrHeight() - screenScale(200) - screenScale(44 * 6));
        
        _dateBgView.frame = CGRectMake(0, screenScale(200)+ screenScale(44 * 5), scrWidth(), scrHeight() - screenScale(200) - screenScale(44 * 5));
        
        [UIView commitAnimations];
        
    }];
    
    _shadowView.hidden = NO;
    _dateBgView.hidden = NO;
    self.myDatePicker.hidden = NO;
}

- (void)sexBtnClick{

    NSLog(@"性别");
    
    FS_MyChangrSexViewController *vc = [[FS_MyChangrSexViewController alloc]init];
    vc.delegate = self;
    [self.navigationController pushViewController:vc animated:YES];
    
}

- (void)getNum:(NSString *)sex{
    
    _sexLabel.text = sex;
}

- (IBAction)secureTextEntryBtnClick:(UIButton*)sender{

    sender.selected = !sender.selected;
    
    if (sender.selected) {
        
        NSString *tempPwdStr = self.pwdTextField.text;
        self.pwdTextField.text = @""; // 这句代码可以防止切换的时候光标偏移
        self.pwdTextField.secureTextEntry = YES;
        self.pwdTextField.text = tempPwdStr;
        
    } else {
        
        NSString *tempPwdStr = self.pwdTextField.text;
        self.pwdTextField.text = @"";
        self.pwdTextField.secureTextEntry = NO;
        self.pwdTextField.text = tempPwdStr;
    }
}

- (void)nextBtnClick{

    NSLog(@"继续");
    
    if (_nameTextField.text.length < 1 ||
        _image == nil ||
        [_sexLabel.text isEqualToString:@"选择性别"] ||
        [_birthdayLabel.text isEqualToString:@"选择生日"]) {
        
        [PublicFunction showAlert:nil message:@"信息不完整" duration:1.0];
        return;
        
    }
    
    if (![TSRegularExpressionUtil validatePassword:_pwdTextField.text]) {
        
        [PublicFunction showAlert:nil message:@"密码长度为6-16位" duration:1.0];
        return;
    }
    
    setPhoneViewController *vc = [[setPhoneViewController alloc]init];
    
    vc.pwd = _pwdTextField.text;
    vc.user_name = _nameTextField.text;
    vc.birthday = _birthdayLabel.text;
    vc.header_img = _image;
    
    if ([_sexLabel.text isEqualToString:@"男"]) {
        
        vc.sex = @"1";
        
    }else{
    
        vc.sex = @"2";
        
    }
    
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)messageBtnClick{

    NSLog(@"协议");
    registerAgreementViewController *vc = [[registerAgreementViewController alloc]init];
    [self.navigationController pushViewController:vc animated:YES];
    
}

#pragma mark ----------------------- 相册／相机 ---------------------

- (void)photoKitController:(STPhotoKitController *)photoKitController resultImage:(UIImage *)resultImage
{
    // [self.imageButton setImage:resultImage forState:UIControlStateNormal];
    
    
    self.image = resultImage;
    //    self.shoppicImage.image = resultImage;
//    self.headImg.image = resultImage;
    [_headImgBtn setImage:resultImage forState:UIControlStateNormal];
    
}

#pragma mark - 2.UIImagePickerController的委托

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info
{
    [picker dismissViewControllerAnimated:YES completion:^{
        UIImage *imageOriginal = [info objectForKey:UIImagePickerControllerOriginalImage];
        STPhotoKitController *photoVC = [STPhotoKitController new];
        [photoVC setDelegate:self];
        [photoVC setImageOriginal:imageOriginal];
        
        [photoVC setSizeClip:CGSizeMake(_headImgBtn.frame.size.width*4, _headImgBtn.frame.size.width*4)];
        
        
        [self presentViewController:photoVC animated:YES completion:nil];
    }];
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
    [picker dismissViewControllerAnimated:YES completion:^(){
    }];
}

#pragma mark - --- event response 事件相应 ---
- (void)editImageSelected
{
    grayView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, DEF_SCREEN_WIDTH, DEF_SCREEN_HEIGHT)];
    grayView.backgroundColor = [UIColor colorWithRed:0 / 255.0f green:0 / 255.0f blue:0 / 255.0f alpha:0.2];
    
    [[UIApplication sharedApplication].keyWindow addSubview:grayView];
    
    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(dismissContactView)];
    [grayView addGestureRecognizer:tapGesture];
    
    [grayView addSubview:self.changeHeadImageView];
    [self.changeHeadImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.mas_equalTo(self.view);
        make.size.mas_equalTo(CGSizeMake(DEF_SCREEN_WIDTH, 160));
    }];
    
    self.changeHeadImageView.layer.cornerRadius = 8;
    [self.changeHeadImageView.takePhotoButton addAction:^(NSInteger tag) {
        UIImagePickerController *controller = [UIImagePickerController imagePickerControllerWithSourceType:UIImagePickerControllerSourceTypeCamera];
        [grayView removeFromSuperview];
        if ([controller isAvailableCamera] && [controller isSupportTakingPhotos]) {
            [controller setDelegate:self];
            [self presentViewController:controller animated:YES completion:nil];
        }else {
            NSLog(@"%s %@", __FUNCTION__, @"相机权限受限");
        }
    }];
    [self.changeHeadImageView.localAlbumButton addAction:^(NSInteger tag) {
        UIImagePickerController *controller = [UIImagePickerController imagePickerControllerWithSourceType:UIImagePickerControllerSourceTypePhotoLibrary];
        [controller setDelegate:self];
        [grayView removeFromSuperview];
        if ([controller isAvailablePhotoLibrary]) {
            [self presentViewController:controller animated:YES completion:nil];
        }
    }];
    [self.changeHeadImageView.closeViewButton addAction:^(NSInteger tag) {
        [self dismissContactView];
    }];
}

- (void)dismissContactView {
    [grayView removeFromSuperview];
}

#pragma mark - ---------- 懒加载 ----------
- (ICN_HeadImageSelView *)changeHeadImageView {
    if (!_changeHeadImageView)
    {
        _changeHeadImageView = [[NSBundle mainBundle] loadNibNamed:@"ICN_HeadImageSelView" owner:self options:nil].lastObject;
    }
    return _changeHeadImageView;
}

@end
